<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Api\Controller;
use Doctrine\DBAL\Driver\AbstractDB2Driver;
use Illuminate\Http\Request;

use Illuminate\Support\Facades\DB;

use EasyWeChat\Factory;



class WechatPayController extends Controller
{


    protected $config;
    protected $payment;

    public function __construct()
    {
        $this->config = [
            'app_id' => 'wxe53ec042d5c44631',

            'mch_id' => '1484391742', // 微信支付MCHID 商户收款账号
            'key' => '548b268162f6561ac230c220783b0e11', // 微信支付KEY


            // 'mch_id'             => '1608868110',
            // 'key'                => 'xvzgdsft34w5y45sagfwgsdf34dfgs3t',   // API 密钥

            // 如需使用敏感接口（如退款、发送红包等）需要配置 API 证书路径(登录商户平台下载 API 证书)
            'cert_path'          => '/www/wwwroot/activity/public/cert/apiclient_cert.pem', // XXX: 绝对路径！！！！
            'key_path'           => '/www/wwwroot/activity/public/cert/apiclient_key.pem',      // XXX: 绝对路径！！！！

            'notify_url'         => '',     // 你也可以在下单时单独设置来想覆盖它

        ];
        $this->payment = Factory::payment($this->config);
        //$this->payment->setSubMerchant('1610272040');  // 子商户 AppID 为可选项

    }

    //预支付订单  type 1扫码订单  2充值订单  3骑行卡订单  4跑腿订单 5跑腿充值订单
    public function prepayOrder($order_id,$openid){


        $order = DB::table('order')->find($order_id);


        if(!$order){
            return false;
        }

        $result = $this->payment->order->unify([
            'body' => "活动报名",
            'out_trade_no' => $order->order_sn,
            'total_fee' => $order->money*100,
            //'spbill_create_ip' => '123.12.12.123', // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
            'notify_url' => env('PAY_NOTIFY'), // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI', // 请对应换成你的支付方式对应的值类型
            'openid' => $openid,
        ]);

        if(isset($result['prepay_id'])){
            return $this->signAgain($result['prepay_id']);

        }else{
            return $this->failed($result);
        }

// $result:
//{
//    "return_code": "SUCCESS",
//    "return_msg": "OK",
//    "appid": "wx2421b1c4390ec4sb",
//    "mch_id": "10000100",
//    "nonce_str": "IITRi8Iabbblz1J",
//    "openid": "oUpF8uMuAJO_M2pxb1Q9zNjWeSs6o",
//    "sign": "7921E432F65EB8ED0CE9755F0E86D72F2",
//    "result_code": "SUCCESS",
//    "prepay_id": "wx201411102639507cbf6ffd8b0779950874",
//    "trade_type": "JSAPI"
//}

    }




    public function signAgain($prepayId){
        $jssdk = $this->payment->jssdk;

        $config = $jssdk->sdkConfig($prepayId); // 返回数组
       // $config = $jssdk->bridgeConfig($prepayId, false); // 返回数组

        return $this->success($config);
    }

    public function notify(){

        //file_put_contents("/www/wwwroot/activity/pay.log",date("Y-m-d H:i:s").'-data-666'."\r\n",FILE_APPEND);

        $response =$this->payment->handlePaidNotify(function($message, $fail){
            //file_put_contents("/www/wwwroot/activity/pay.log",date("Y-m-d H:i:s").'-data-'.json_encode($message)."\r\n",FILE_APPEND);


            // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
            $order_sn = $message['out_trade_no'];
            $order = Db::table('order')->where('order_sn',$order_sn)->first();

            if (!$order || $order->pay_status==1) { // 如果订单不存在 或者 订单已经支付过了
                return true; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
            }

            ///////////// <- 建议在这里调用微信的【订单查询】接口查一下该笔订单的情况，确认是已经支付 /////////////
            //file_put_contents("/www/wwwroot/electric-vehicle/pay.log",date("Y-m-d H:i:s").'-return_code-'."$message->return_code"."\r\n",FILE_APPEND);

            if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
                //file_put_contents("/www/wwwroot/activity/pay.log",date("Y-m-d H:i:s").'-return_code-'."\r\n",FILE_APPEND);

                // 用户是否支付成功
                if ($message['result_code'] === 'SUCCESS') {
                    //file_put_contents("/www/wwwroot/activity/pay.log",date("Y-m-d H:i:s").'-result_code-'."\r\n",FILE_APPEND);

                    DB::table('order')->where('order_sn',$order_sn)->update(['pay_status'=>1,'pay_time'=>date("Y-m-d H:i:s"),'xml'=>json_encode($message)]);
                    $order_id = DB::table('order')->where('order_sn',$order_sn)->value('id');
                    DB::table('order_user')->where('order_id',$order_id)->update(['pay_status'=>1]);

                    // 用户支付失败
                } elseif ($message['result_code'] === 'FAIL') {
//                    $order->status = 'paid_fail';
                    DB::table('order')->where('order_sn',$order_sn)->update(['pay_time'=>date("Y-m-d H:i:s"),'xml'=>json_encode($message)]);

                }
            } else {
                return $fail('通信失败，请稍后再通知我');
            }

//            $order->save(); // 保存订单

            return true; // 返回处理完成
        });

        return $response->send(); // return $response;
    }

    public function refund($order,$refund_money){

        $refund_no = date('YmdHis',time()).rand(1000,9999);
        // 参数分别为：商户订单号、商户退款单号、订单金额、退款金额、其他参数
        $result = $this->payment->refund->byOutTradeNumber($order['order_sn'], $refund_no, $order['money']*100, $refund_money*100, [
            // 可在此处传入其他参数，详细参数见微信支付文档
            'refund_desc' => '订单退款',
        ]);


        return $result;
    }

    public function test(){
        $message = json_decode('{"appid":"wxa0a4e4c7ca0b93ad","bank_type":"OTHERS","cash_fee":"1","fee_type":"CNY","is_subscribe":"N","mch_id":"1507346331","nonce_str":"61386150d7771","openid":"oxjr85ZE7wyrDrqMFN3mMtgjMR_o","out_trade_no":"recharge16310848809628","result_code":"SUCCESS","return_code":"SUCCESS","sign":"FEE2F0AF66DFD486DAF0BA0DCB3D944A","time_end":"20210908150824","total_fee":"1","trade_type":"JSAPI","transaction_id":"4200001222202109088152219411"}',true);
        update_pay_status($message);
    }

}
